package org.techmore.activity;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.techmore.R;
import org.techmore.biz.CouponMapActivityDataHandler;
import org.techmore.biz.CouponMapOverlayView;
import org.techmore.zxing.client.android.CaptureActivity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

public class CouponMapActivity extends MapActivity {
	
	private MapView mapView = null;
	private MapController mapController = null;
	private List<Overlay> overlays = null;
	private View mapPopView = null;
	
	private LocationManager locationManager = null;
	private double longitude = 0;
	private double latitude = 0;
	
	private int seekbarSize = 0;
	private SeekBar couponSeekBar = null;
	
	
	@Override
	protected void onCreate(Bundle icicle) {
		// TODO Auto-generated method stub
		super.onCreate(icicle);
		setScreenOrientation();
		
		LinearLayout linearLayout = initContentView();
		
		setContentView(linearLayout);
		
		prepareMap(linearLayout);
		
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		//longitude=121.639718&latitude=24.955585&range=50	
		getLocation();
		longitude = 121.639718;
		latitude = 24.955585;
		
		Intent intent = getIntent();
		int range = intent.getIntExtra("range", 50);
		if(null != couponSeekBar){
			couponSeekBar.setProgress(range);
		}
		double rangeD = (double)range/100*100;
		
		initMapView();
		initStore(rangeD);
	}
	
	private Timer timer = new Timer("xxx",true);
	private Handler getLastLocationHandler = null;
//	private Handler getSatelliteHandler = null;
	private class GetLastLocation extends TimerTask {
		@Override
		public void run() {
			Message message = new Message();      
			message.what = 1;      
			getLastLocationHandler.sendMessage(message); 
		}
	}
	
	
//	private Iterator<GpsSatellite> iterator = null;
//	private class GetSatellite extends TimerTask{
//		@Override
//		public void run() {
//			Message message = new Message();      
//			message.what = 2;      
//			getSatelliteHandler.sendMessage(message); 
//		}
//	}
		 
	
	private void getLocation() {
		
		locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
		
		Criteria mcriteria = new Criteria();
        mcriteria.setAccuracy(Criteria.ACCURACY_FINE);// 设置为最大精度
        mcriteria.setAltitudeRequired(false);// 不要求海拔信息
        mcriteria.setBearingRequired(false);// 不要求方位信息
        mcriteria.setCostAllowed(true);// 是否允许付费
        mcriteria.setPowerRequirement(Criteria.POWER_LOW);// 对电量要求
        final String strLocationProvider = locationManager.getBestProvider(mcriteria, true);
        
        Location location = null;
        List<String> list = locationManager.getProviders(mcriteria, false);
        for(int i=0;i<list.size();i++){
        	System.out.println("1111111111:"+list.get(i));
        	location = locationManager.getLastKnownLocation(list.get(i));
        	if(null == location && i<list.size()){
        		continue;
        	}else{
        		break;
        	}
        }
        
		if(null != location){
			initUserLocal(location.getLatitude(),location.getLongitude());
			System.out.println("1111111:="+location.getLatitude()+":"+location.getLongitude());
		}
        
		
		getLastLocationHandler = new Handler(Looper.myLooper()){
			public void handleMessage(android.os.Message msg) {
				super.handleMessage(msg);
				locationManager.removeUpdates(locationListener);
				
				locationManager.requestLocationUpdates(strLocationProvider, 200, 0,locationListener);
			};
		};
		
		if (!locationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
       	 	Toast.makeText(this, "請先開啟GPS！", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
            startActivityForResult(intent,0); //0表示去開啟gps//此为设置完成后返回到获取界面
		}else{
			//取出为null提示gps不可用
//			Location location = locationManager.getLastKnownLocation(Context.LOCATION_SERVICE);
//			timer.schedule(new GetSatellite(), 10, 1000);
			timer.schedule(new GetLastLocation(), 5, 2000);
		}
		
		
//		getSatelliteHandler = new Handler(Looper.myLooper()){
//			@Override
//			public void handleMessage(Message msg) {
//				super.handleMessage(msg);
//				iterator = locationManager.getGpsStatus(null).getSatellites().iterator();
//				int count = 0;
//				while (iterator.hasNext()) {
//				        count++;
//				}
//				setSatellite(count);
//				System.out.println(count);
//			}
//		};
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		//取出为null提示gps不可用
//		timer.schedule(new GetSatellite(), 10, 1000);
//		timer.schedule(new GetLastLocation(), 5, 5000);
		getLocation();
	}
	
	private void initMapView(){
    	//设置为交通模式
		//mapView.setTraffic(true);
		//设置为卫星模式
		//mMapView.setSatellite(true); 
		//设置为街景模式
		mapView.setStreetView(false);
    	mapView.setEnabled(true);
    	mapView.setClickable(true);
    	mapView.setBuiltInZoomControls(true);
    	mapController.setZoom(12); 
    }
	
	private CouponMapOverlayView couponMapOverlayViewCache = null;
	private CouponMapOverlayView couponMapOverlayView = null;
	private void initUserLocal(double latitude, double longitude){
		if(null!=couponMapOverlayViewCache){
			overlays.remove(couponMapOverlayViewCache);
		}
		//设置中心点
    	GeoPoint geo = new GeoPoint((int)(latitude*1E6), (int)(longitude*1E6));
    	OverlayItem overlayitem = new OverlayItem(geo, this.getResources().getString(R.string.mapUserlocation), geo.getLatitudeE6()+"##"+geo.getLongitudeE6());
    	couponMapOverlayView = new CouponMapOverlayView(this, mapView, mapPopView,
    			this.getResources().getDrawable(R.drawable.location_center));
    	couponMapOverlayView.addOverlay(overlayitem);
    	overlays.add(couponMapOverlayView);
    	couponMapOverlayViewCache = couponMapOverlayView;
    	
    	mapController.animateTo(geo);
	}
//	private void setSatellite(int k){
//		TextView couponMapSatellite = (TextView) this.findViewById(R.id.couponMapSatellite);
//		couponMapSatellite.setText("衛星個數:"+k);
//	}
	
	private void initStore(double rangeD){
    	CouponMapActivityDataHandler.getInstance().getLBSStoreByUrl(this, mapView, overlays, mapPopView,rangeD,String.valueOf(latitude),String.valueOf(longitude));
    	mapView.invalidate();
	}
	
	private void prepareMap(LinearLayout linearLayout) {
		mapPopView = LayoutInflater.from(this).inflate(R.layout.techmore_map_pop, null);
		
		mapView = (MapView) linearLayout.findViewById(R.id.couponMapLayout_MapView);
		
		mapController = mapView.getController();
		overlays = mapView.getOverlays();
	}

	private TextView couponMapNearText = null;
	private LinearLayout initContentView() {
		LinearLayout linearLayout = (LinearLayout)LayoutInflater.from(this).inflate(R.layout.techmore_couponmap, null);
//		RelativeLayout titleRelativeLayout = (RelativeLayout) linearLayout.findViewById(R.id.titleRelativeLayout);
        RelativeLayout footerRelativeLayout = (RelativeLayout) linearLayout.findViewById(R.id.footerRelativeLayout);
        FrameLayout couponMapContentLayout = (FrameLayout) linearLayout.findViewById(R.id.couponMapContentLayout);
        
        LayoutParams contentLayoutParams = couponMapContentLayout.getLayoutParams();
        //獲取屏幕高度
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        Integer contentScrollViewHeight = displayMetrics.heightPixels;
        contentLayoutParams.height = contentScrollViewHeight - footerRelativeLayout.getLayoutParams().height - 30;
        couponMapContentLayout.setLayoutParams(contentLayoutParams);
        
        couponMapNearText = (TextView) couponMapContentLayout.findViewById(R.id.couponMapNearText);
        couponSeekBar = (SeekBar) couponMapContentLayout.findViewById(R.id.couponSeekBar);
        
        couponSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub
				seekbarSize = seekBar.getProgress();
				couponMapNearText.setText((double)seekbarSize/100*100+"公里內");
			}
			
			@Override
			public void onStartTrackingTouch(SeekBar seekBar) { }
			@Override
			public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { }
		});
        
        Button couponMapSearch = (Button) couponMapContentLayout.findViewById(R.id.couponMapSearch);
        couponMapSearch.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(CouponMapActivity.this,CouponMapActivity.class);
				intent.putExtra("range", seekbarSize);
				CouponMapActivity.this.startActivity(intent);
				overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
				CouponMapActivity.this.finish();
			}
		});
        
        
        
		adapterFootButton(footerRelativeLayout);
		return linearLayout;
	}
	
	
	/**
     * 設置屏幕方向
     */
    private void setScreenOrientation(){
    	getWindow().requestFeature(Window.FEATURE_NO_TITLE);
    	setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);		//豎屏
//    	setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);		//橫屏
    }
	
    private void adapterFootButton(RelativeLayout linearLayout){
    	
    	//獲取屏幕高度
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        Integer windowWidth = displayMetrics.widthPixels;
        
    	LinearLayout couponListButton = (LinearLayout) linearLayout.findViewById(R.id.couponListButton);
        LinearLayout nearCouponListButton = (LinearLayout) linearLayout.findViewById(R.id.nearCouponListButton);
    	LinearLayout myCouponListButton = (LinearLayout) linearLayout.findViewById(R.id.myCouponListButton);
    	LinearLayout couponScanner = (LinearLayout) linearLayout.findViewById(R.id.couponScanner);
    	
    	RelativeLayout.LayoutParams layoutParams = null;
    	
    	if(240<windowWidth){
    		layoutParams = (android.widget.RelativeLayout.LayoutParams) couponListButton.getLayoutParams();
    		layoutParams.setMargins((windowWidth-240)/5, 0, 0, 0 );
    		couponListButton.setLayoutParams(layoutParams);
    		
    		layoutParams = (android.widget.RelativeLayout.LayoutParams) nearCouponListButton.getLayoutParams();
    		layoutParams.setMargins((windowWidth-240)/5, 0, 0, 0 );
    		nearCouponListButton.setLayoutParams(layoutParams);
    		
    		layoutParams = (android.widget.RelativeLayout.LayoutParams) myCouponListButton.getLayoutParams();
    		layoutParams.setMargins((windowWidth-240)/5, 0, 0, 0 );
    		myCouponListButton.setLayoutParams(layoutParams);
    		
    		layoutParams = (android.widget.RelativeLayout.LayoutParams) couponScanner.getLayoutParams();
    		layoutParams.setMargins((windowWidth-240)/5, 0, 0, 0 );
    		couponScanner.setLayoutParams(layoutParams);
    	}
    	couponListButton.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(CouponMapActivity.this, CouponListActivity.class);
				CouponMapActivity.this.startActivity(intent);
				overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
//				MyCouponListActivity.this.finish();
				return false;
			}
		});
    	
    	couponScanner.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(CouponMapActivity.this);
				if(preferences.getBoolean("isLogin",false)){
					Intent intent = new Intent();
					intent.setClass(CouponMapActivity.this, CaptureActivity.class);
					CouponMapActivity.this.startActivity(intent);
					overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
				}else{
					CouponMapActivity.this.startActivity(new Intent(CouponMapActivity.this,CouponLoginActivity.class));
				}
				return false;
			}
		});
    	
    	myCouponListButton.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(CouponMapActivity.this, MyCouponListActivity.class);
				CouponMapActivity.this.startActivity(intent);
				overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
//				CouponListActivity.this.finish();
				return false;
			}
		});
    }
    
    private LocationListener locationListener = new LocationListener() {
		public void onLocationChanged(Location location) { 
//			timer.cancel();
			initUserLocal(location.getLatitude(),location.getLongitude());
			locationManager.removeUpdates(this);
			System.out.println("onLocationChanged:="+location.getLatitude()+":"+location.getLongitude());
			
		}
		public void onProviderDisabled(String provider) { }
		public void onProviderEnabled(String provider) {
			System.out.println("onProviderEnabled:"+provider);
		}
		public void onStatusChanged(String provider, int status, Bundle extras) {
			System.out.println("onStatusChanged:"+provider);
		}
	};
	
	protected void onPause() {
		super.onPause();
	};
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		timer.cancel();timer.purge();
		locationManager.removeUpdates(locationListener);
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

}
